package www.dianbaozu.com.ui.server

import android.os.Bundle
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.NonNull
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.entity.node.BaseNode
import com.chad.library.adapter.base.listener.OnItemLongClickListener
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.dylanc.loadinghelper.LoadingHelper
import com.dylanc.loadinghelper.ViewType
import com.lxj.xpopup.core.BasePopupView
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.api.SessionHelper
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentServerListBinding
import www.dianbaozu.com.extension.requestServerDetails
import www.dianbaozu.com.extension.requestUniversally
import www.dianbaozu.com.ui.server.ServerListFirstProvider.Companion.EXPAND_COLLAPSE_PAYLOAD
import www.wen.com.common.lib.base.fragment.BaseListFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.CLEAR_PREVIEW_INFO_KEY
import www.wen.com.common.lib.helper.loading.KeyHelper.MMKV_ID
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESHING_SERVER_LIST_KEY
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESHING_SERVER_LIST_KEY1
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESHING_SERVER_LIST_KEY4
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESHING_SERVER_LIST_KEY5
import www.wen.com.common.lib.helper.loading.KeyHelper.REFRESHING_SERVER_LIST_KEY6
import www.wen.com.common.lib.helper.loading.KeyHelper.TEAM_UNREAD_KEY
import www.wen.com.common.lib.helper.loading.LoadingAdapter
import www.wen.com.common.lib.helper.loading.NoTitleAdapter
import www.wen.com.common.lib.util.SpUtil

/**
 * @author WEN
 * @Description:首页-服务 右边的分组列表
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class ServerListFragment :
        BaseListFragment<FragmentServerListBinding, ServerGroupEntity, BaseNode>(), OnItemLongClickListener {


    private lateinit var mServerNameView: TextView

    private lateinit var mServerListAdapter: ServerListAdapter

    private lateinit var mServerTreeEntity: ServerSelfListEntity.Content

    private val serverListViewModel: ServerListViewModel by viewModels()

    override val isAddHead: Boolean
        get() = true

    override val mIsEnableAdapterLoadMore: Boolean
        get() = false

    override val mIsEnableSmartRefreshLoadMore: Boolean
        get() = false

    override val viewModel: BaseViewModel
        get() = serverListViewModel

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?,
    ): View? {
        mServerTreeEntity = requireArguments().getParcelable(BUNDLE_DATA)!!
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun isEnableLoadingHelper(): Boolean = true

    override fun configurationLoadingHelper(loadingHelper: LoadingHelper): LoadingHelper {
        loadingHelper.register(ViewType.TITLE, getTitleBarUniversalAdapter())
        loadingHelper.register(ViewType.LOADING, LoadingAdapter(R.color.color1B1D22))
        loadingHelper.setDecorHeader(ViewType.TITLE)
        return loadingHelper
    }

    override fun getTitleBarUniversalAdapter(): NoTitleAdapter = NoTitleAdapter(requireActivity())

    override fun getLayoutId(): Int = R.layout.fragment_server_list

    override fun lazyInitView() {
        super.lazyInitView()
        observeListen()
        launchRequest(false)
    }

    private fun launchRequest(isRefresh: Boolean) {
        serverListViewModel.mOwnUserId = mServerTreeEntity.ownUserId
        serverListViewModel.requestGeneralListData(requiredParameter = mServerTreeEntity.serverId, isRefresh = isRefresh)
        mServerListAdapter.setOnItemLongClickListener(this@ServerListFragment)
    }

    override fun onReload() {
        launchRequest(false)
    }

    override fun onRefresh(@NonNull refreshLayout: RefreshLayout) {
        launchRequest(true)
//        postObject(REFRESHING_SERVER_LIST_KEY1,false)
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        mServerListAdapter.expandOrCollapse(
                position,
                true,
                true,
                EXPAND_COLLAPSE_PAYLOAD
        )
    }

    override fun onItemLongClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int): Boolean {
        return if (view.id == R.id.group) {
            if(mServerTreeEntity.ownUserId == SpUtil.decodeString(MMKV_ID)){
                serverListViewModel.requestUniversally(
                        viewModelScope = lifecycleScope,
                        isShowToastTip = false,
                        request = { appDataManage ->
                            appDataManage.requestServerGroupList(mServerTreeEntity.serverId)
                        }
                ) { groups ->
                    val data: ArrayList<Parcelable> = ArrayList()
                    groups.content.forEach {
                        data.add(ServerGroupIncludeEntity(1, it))
                        it.channelVO.forEach { channelVO ->
                            channelVO.groupType = it.groupType
                            data.add(ServerGroupIncludeEntity(2, channelVO = channelVO))
                        }
                    }

                    nav(R.id.action_mainFragment_to_channelManagementFragment, Bundle().apply {
                        putParcelableArrayList(BUNDLE_DATA, data)
                        putString(KeyHelper.BUNDLE_SERVER_ID, mServerTreeEntity.serverId)
                    })
                }
                true
            }else{
                false
            }
        } else {
            false
        }
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

        when (view.id) {
            R.id.ivAdd -> {
                val content = adapter.data[position] as ServerGroupEntity.Content
                nav(R.id.action_mainFragment_to_channelCreateFragment, Bundle().apply {
                    putParcelable(BUNDLE_DATA, BundleEntitySealed.BundleEntityFromServerSealed(content.groupId,
                            content.groupName,
                            content.serverId,
                            NavigationFromType.FROM_SERVER,
                            mServerTreeEntity.serverName
                    ))
                })

            }

            R.id.channel -> {
                if (mServerTreeEntity.serverStatus == 1) {
                    CreateXPopupHelper.createInformPopupView(PopupViewEntity().apply {
                        isShow = true
                        context = requireActivity()
                        title = getString(R.string.the_server_is_blocked)
                        content = "因以下原因,服务器「${mServerTreeEntity.serverName}」 已被封禁：\n\n该服务器因「${mServerTreeEntity.forbidReason}」被封禁，在 ${mServerTreeEntity.unForbidTime} 解封前，该服务器将无法进入频道进行聊天。"
                        confirmContent = getString(R.string.got_it)
                        confirmFunction = ::confirmContent
                    })
                } else {
                    if (mServerTreeEntity.serverGroups != null) {
                        CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
                            context = requireActivity()
                            standardAlertPopupViewTitle = "加入服务器"
                            isShow = true
                            standardAlertPopupViewCancelContent = "取消"
                            standardAlertPopupViewConfirmContent = "加入"
                            standardAlertPopupViewContent = "加入服务器「${mServerTreeEntity.serverName}」以进行聊天"
                            confirmFunction = {
                                it.dismiss()
                                serverListViewModel.requestUniversally(
                                        tipLoading = getString(R.string.com_joining_server),
                                        tipSuccess = getString(R.string.success_added),
                                        viewModelScope = lifecycleScope,
                                        request = { appDataManage ->
                                            appDataManage.requestInviteOrAdd("add", RequestBodyParameter(serverId = mServerTreeEntity.serverId))
                                        }
                                ) {
                                    NIMHelper.addAllTeamToRecentContact()
                                    mServerTreeEntity.serverGroups = null
                                    val channelVO = adapter.data[position] as ServerGroupEntity.Content.ChannelVO
                                    SessionHelper.startTeamSession(requireContext(), channelVO.teamId, channelVO)
                                    postObject(CLEAR_PREVIEW_INFO_KEY, Object())
                                }
                            }
                        })
                    } else {
                        val channelVO = adapter.data[position] as ServerGroupEntity.Content.ChannelVO
                        SessionHelper.startTeamSession(requireContext(), channelVO.teamId, channelVO)
                    }
                }
            }
        }
    }

    private fun confirmContent(popupView: BasePopupView) {
        popupView.dismiss()
    }

    private fun observeListen() {
        serverListViewModel.uiState.observe(this) {
            if (it.showSuccess != null) {
                NIMHelper.addAllTeamToRecentContact()
                mServerListAdapter.setList(it.showSuccess)
            }
        }
        //刷新列表
        observeObject(REFRESHING_SERVER_LIST_KEY, this, ServerSelfListEntity.Content::class.java) {
            dataBinding.smartRefreshLayout.isVisible = true
            mServerTreeEntity = this
            mServerNameView.text = mServerTreeEntity.serverName
            serverListViewModel.mJob?.cancel()
            launchRequest(false)
        }
        //清空所有数据和隐藏头部
        observeObject(REFRESHING_SERVER_LIST_KEY5, this, Any::class.java) {
            dataBinding.smartRefreshLayout.isVisible = false
        }

        //刷新列表
        observeObject(REFRESHING_SERVER_LIST_KEY4, this, ServerUpdateInfoEntity::class.java) {
            dataBinding.smartRefreshLayout.isVisible = true
            mServerTreeEntity.serverName = serverName!!
            mServerTreeEntity.serverId = serverId!!
            mServerNameView.text = mServerTreeEntity.serverName
            serverListViewModel.mJob?.cancel()
            launchRequest(false)
        }
        //更新服务器名字
        observeObject(
                KeyHelper.UPDATE_SERVER_INFORMATION_KEY,
                this,
                ServerUpdateInfoEntity::class.java
        ) {
            if (serverId == mServerTreeEntity.serverId) {
                serverName?.also {
                    mServerNameView.text = it
                    mServerTreeEntity.serverName = it
                }
            }
        }
        //刷新列表
        observeObject(REFRESHING_SERVER_LIST_KEY1, this, Any::class.java) {
            dataBinding.smartRefreshLayout.isVisible = true
            serverListViewModel.mJob?.cancel()
            if (this is Boolean) {
                launchRequest(this)
            } else {
                launchRequest(false)
            }
        }
        //如果serverId相等则刷新列表
        observeObject(REFRESHING_SERVER_LIST_KEY6, this, String::class.java) {
            if(mServerTreeEntity.serverId == this){
                launchRequest(false)
            }
        }

        //未读数更新监听
        observeObject(TEAM_UNREAD_KEY, this, TeamUnreadEntity::class.java) {
            mServerListAdapter.data.forEachIndexed { index, node ->
                if (node is ServerGroupEntity.Content.ChannelVO) {
                    if (node.teamId == this.contactId) {
                        node.unreadCount = this.unreadCount
                        mServerListAdapter.notifyItemChanged(index + 1)
                        return@forEachIndexed
                    }
                }
            }
        }
    }

    override val mRecyclerView: RecyclerView get() = dataBinding.rvGroupList

    override val mSmartRefreshLayout: SmartRefreshLayout get() = dataBinding.smartRefreshLayout

    override fun provideAdapter(): BaseQuickAdapter<BaseNode, BaseViewHolder> =
            ServerListAdapter(mServerTreeEntity.ownUserId).apply {
                mServerListAdapter = this
            }



    override fun addHeadProxy(adapter: BaseQuickAdapter<*, *>) {
        LayoutInflater.from(requireActivity()).inflate(R.layout.head_home_server_title, mRecyclerView, false).run {
                findViewById<View>(R.id.ivMore).setOnClickListener(this@ServerListFragment)
                    mServerNameView = findViewById<TextView>(R.id.tv).apply {
                        text = mServerTreeEntity.serverName
                    }
                    adapter.addHeaderView(this)
                }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.ivMore -> {
                if (mServerTreeEntity.serverGroups != null) {
                    CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
                        context = requireActivity()
                        standardAlertPopupViewTitle = "加入服务器"
                        isShow = true
                        standardAlertPopupViewCancelContent = "取消"
                        standardAlertPopupViewConfirmContent = "加入"
                        standardAlertPopupViewContent = "加入服务器「${mServerTreeEntity.serverName}」以进行聊天"
                        confirmFunction = {
                            it.dismiss()
                            serverListViewModel.requestUniversally(
                                    viewModelScope = lifecycleScope,
                                    tipLoading = getString(R.string.com_joining_server),
                                    tipSuccess = getString(R.string.success_added),
                                    request = { appDataManage ->
                                        appDataManage.requestInviteOrAdd("add", RequestBodyParameter(serverId = mServerTreeEntity.serverId))
                                    }
                            ) {
                                NIMHelper.addAllTeamToRecentContact()
                                mServerTreeEntity.serverGroups = null
                                postObject(CLEAR_PREVIEW_INFO_KEY, Object())
                            }
                        }
                    })
                } else {
                    serverListViewModel.requestServerDetails(
                            viewModelScope = lifecycleScope,
                            mServerTreeEntity.serverId,
                    ) {
                        nav(R.id.action_mainFragment_to_serverDetailsFragment, Bundle().apply {
                            putParcelable(BUNDLE_DATA, it.apply {
                                fromType = NavigationFromType.FROM_SERVER
                            })
                        })
                    }
                }
            }
        }

    }

}



